
package com.onesports.intelligent.k12.polarlight.resolver;

import com.onesports.intelligent.k12.polarlight.annotation.OrganizationId;
import com.onesports.intelligent.k12.polarlight.annotation.StaffID;
import com.onesports.intelligent.k12.polarlight.annotation.UID;
import com.onesports.intelligent.k12.polarlight.security.DomainUserDetails;
import com.onesports.intelligent.k12.polarlight.security.SecurityUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import java.util.Optional;

public class TokenArgumentResolver implements HandlerMethodArgumentResolver {

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.hasParameterAnnotation(UID.class)
                || parameter.hasParameterAnnotation(OrganizationId.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
                                  NativeWebRequest webRequest, WebDataBinderFactory binderFactory) {
        if (parameter.hasParameterAnnotation(UID.class)) {
            Optional<DomainUserDetails> user = SecurityUtils.getCurrentUserDetails();
            if (user.isPresent() && StringUtils.isNotEmpty(user.get().getCurrent())) {
                return user.get().getCurrent();
            }
        } else if (parameter.hasParameterAnnotation(OrganizationId.class)) {
            Optional<DomainUserDetails> user = SecurityUtils.getCurrentUserDetails();
            if (user.isPresent() && StringUtils.isNotEmpty(user.get().getOrganizationId())) {
                return user.get().getOrganizationId();
            }
        } else if (parameter.hasParameterAnnotation(StaffID.class)) {
            Optional<DomainUserDetails> user = SecurityUtils.getCurrentUserDetails();
            if (user.isPresent() && StringUtils.isNotEmpty(user.get().getStaffId())) {
                return user.get().getStaffId();
            }
        }

        return null;
    }

}
